const { Configuration, OpenAIApi } = require('openai')
const inquirer = require('inquirer')

const configuration = new Configuration({
  apiKey: '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',
})
const openai = new OpenAIApi(configuration)

async function getCompletion(prompt) {
  try {
    const completion = await openai.createCompletion({
      model: 'text-davinci-003',
      prompt,
      max_tokens: 500,
    })

    return completion.data.choices[0].text
  } catch (error) {
    if (error.response) {
      console.log(error.response.status)
      console.log(error.response.data)
    } else {
      console.log(error.message)
    }

    return 'erro'
  }
}

const prompt = inquirer.createPromptModule()

function main() {
  prompt([
    {
      type: 'input',
      message: 'Q:',
      name: 'question',
    },
  ])
    .then((answers) => {
      if (!answers.question) {
        console.log('question is empty!')
        main()
        return
      }

      return getCompletion(answers.question).then((answer) => {
        console.log(answer, '\n')
        main()
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

main()
